import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/components/loading_dialog.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/model/user_info.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/my/view_model/my_view_model.dart';
import 'package:line_awesome_icons/line_awesome_icons.dart';
import 'package:provider/provider.dart';

import 'view_model/user_info_editor_model.dart';

class UserInfoEditorView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserInfoEditorViewState();
  }
}

class _UserInfoEditorViewState extends State<UserInfoEditorView> {
  UserInfoEditorModel userInfoModel;
  MyViewModel myViewModel;
  LoadingDialog loading;

  @override
  void initState() {
    super.initState();
    loading = new LoadingDialog(context);
  }

  @override
  void didChangeDependencies() {
    userInfoModel = Provider.of<UserInfoEditorModel>(context);
    myViewModel = Provider.of<MyViewModel>(context);

    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('编辑'),
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: FutureProvider(
          create: (cxt) async {
            await userInfoModel.load();
          },
          child: _createBody(),
          lazy: false,
        ),
      ),
    );
  }

  Widget _createBody() {
    var user = userInfoModel.userInfo;
    if (user == null) return LoadingWidget();
    var formater = new DateFormat('yyyy-MM-dd');
    return SingleChildScrollView(
      child: Column(
        children: ListTile.divideTiles(
          color: Colors.black12,
          tiles: [
            _createField('姓名', user.realname),
            _createField('性别', user.gender == Gender.Girl ? '女' : '男'),
            _createField('身份证号', user.identityCard),
            _createField(
              '出生日期',
              user.birthday == null ? null : formater.format(user.birthday),
              onTap: () async {
                var now = DateTime.now();
                var birthday = await showDatePicker(
                  context: context,
                  firstDate: DateTime.parse('1900-01-01'),
                  initialDate: user.birthday ?? now,
                  lastDate: now,
                );
                if (birthday != null) {
                  await userInfoModel.updateBirthday(birthday);
                  Fluttertoast.showToast(msg: '修改生日成功');
                }
              },
            ),
            _createField('手机号', user.mobile, onTap: () {
              showMobileEditor();
            }),
            _createField('员工编号', user.jobNumber),
            _createField('部门', user.deptName),
            _createField('工种', user.craftName),
            _createField('职务', user.duty),
            _createField('职称', user.professionalTitle),
            _createField('文化程度', user.education),
            _createField('政治面貌', user.politicCountenance),
            _createField('入党时间', user.joinThePartyTime == null ? null : formater.format(user.joinThePartyTime)),
            _createField('籍贯', user.nativePlace),
          ],
        ).toList()
          ..insert(0, _createHead()),
      ),
    );
  }

  Widget _createHead() {
    return Container(
      padding: EdgeInsets.fromLTRB(0, 40, 0, 30),
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          _createCircleAvatar(),
          FlatButton(
            child: Text('更换头像'),
            textColor: Colors.black54,
            onPressed: uploadAvatar,
          ),
        ],
      ),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 5,
            color: Color.fromRGBO(240, 240, 240, 1),
          ),
        ),
      ),
    );
  }

  Widget _createCircleAvatar() {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(240, 240, 240, 1),
            blurRadius: 3,
          ),
        ],
      ),
      child: ClipOval(
        child: CachedNetworkImage(
          imageUrl: userInfoModel.userInfo.headUrl ?? '',
          width: 100,
          height: 100,
          fit: BoxFit.cover,
          errorWidget: (_, __, ___) => Image.asset(
            R.assetsImgLogo,
            width: 100,
            height: 100,
          ),
        ),
      ),
    );
  }

  Widget _createField(String title, String subTitle, {Function onTap}) {
    if (subTitle == null || subTitle.isEmpty) {
      subTitle = '未完善';
    }

    var titleWidget = Text(
      title,
      style: TextStyle(
        color: Colors.black87,
        fontSize: 14,
      ),
    );

    var valueWidget = Text(
      subTitle,
      textAlign: TextAlign.right,
      style: TextStyle(
        fontSize: 14,
        color: Colors.black54,
      ),
    );

    bool canEdit = (onTap != null);
    return ListTile(
      dense: true,
      contentPadding: EdgeInsets.fromLTRB(20, 0, 10, 0),
      leading: titleWidget,
      title: valueWidget,
      trailing: Icon(
        LineAwesomeIcons.angle_right,
        size: 18,
        color: canEdit ? Colors.black54 : Colors.white,
      ),
      onTap: onTap,
    );
  }

  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
  TextEditingController mobileTextController;
  void showMobileEditor() {
    mobileTextController = new TextEditingController(text: userInfoModel.userInfo.mobile);
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('修改手机号码'),
            content: phoneField(),
            actions: [
              FlatButton(
                textColor: Colors.black54,
                child: Text('取消'),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                textColor: Theme.of(context).primaryColor,
                child: Text('确认'),
                onPressed: () {
                  if (_fbKey.currentState.validate()) {
                    userInfoModel.updateMobile(mobileTextController.text);
                    Navigator.pop(context);
                    Fluttertoast.showToast(msg: '修改手机号码成功');
                  }
                },
              ),
            ],
          );
        });
  }

  Widget phoneField() {
    return FormBuilder(
      key: _fbKey,
      autovalidate: true,
      child: FormBuilderTextField(
        controller: mobileTextController,
        decoration: InputDecoration(
          icon: Icon(LineAwesomeIcons.mobile),
          hintText: '手机号码',
        ),
        attribute: 'mobile',
        validators: [
          FormBuilderValidators.pattern(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$',
            errorText: '请输入正确的手机号码',
          ),
        ],
      ),
    );
  }

  Future uploadAvatar() async {
    var img = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (img != null) {
      loading.show();
      await userInfoModel.updateAvatar(img);
      await myViewModel.load();
      loading.dismiss();
      Fluttertoast.showToast(msg: '修改头像成功');
    }
  }
}
